This function reads one line of characters from the given file and stores them in the
character array provided by the caller.
The function tests for end of file (feof), and operating system errors on read (ferror).
If either condition occurs, a 0 is returned to indicate the failure.
Arguments
- *file Pointer to the FILE struct representing the file to read from.
- *line Point to the character array to store the results in.
- max Maximum number of characters the array will hold. Leave room for the zero at the end.
Return
Returns 0 on failure, 1 on success.
Notes
This may leave a dangling CR or LF as the first character to be read next
time. That's why it ignores empty lines.
Code
//##############################################################################
// read one line from the specified file. the newline char is discarded
// return 0 on failure, 1 on success
//##############################################################################
int readline(FILE *file, char *line, int max)
{
int i = 0;
while(i < max - 1) {
char result = fgetc(file);
if (feof(file) || ferror(file)) return (0);
if (i == 0 && result == '\n') continue;
if (i == 0 && result == '\r') continue;
if (result == '\n') break;
if (result == '\r') break;
line[i++] = result;
}
line[i] = '\0';
return (1);
}
Typical Usage
if (infile) {
char line[1001];
while (readline(infile, line, 1000)) {
printf("%s\n", line);
}
fclose(infile);
}